package com.mfz.common.units

import com.mfz.common.definition.symbol.Flag
import com.mfz.common.definition.symbol.Type
import org.postgresql.jdbc.PgArray
import java.text.SimpleDateFormat
import java.util.*


val DATE_FORMAT = "yyyy-MM-dd HH:mm:ss"
/**
 *
 * create by 2019-06-19.
 * @author yimin
 */
/**
 * 转换一个对象至JSON的值显示.
 *
 * @param obj 要转换的对象
 * @return 对象为空，返回""
 */
fun transformToJSONString(name: String, obj: Any?): String {
	if (obj == null) return "\"\""
	//这里增加一个对特殊字段的处理
	return when (name.toLowerCase()) {
		FLAG -> {
			if (obj is Int) {
				"\"" + Flag.firstOrNull { obj == it.id }?.name + "\""
			} else
				"\"$obj\""
		}
		TYPE -> {
			if (obj is Int) {
				"\"" + Type.firstOrNull { obj == it.id }?.name + "\""
			} else
				"\"$obj\""
		}
		else -> when (obj) {
			is String -> "\"" + handleString(obj) + "\""
			is Int, is Long -> obj.toString()
			is Date -> "\"" + SimpleDateFormat(DATE_FORMAT).format(obj) + "\""
			is Array<*> -> getArrayStrings(obj)
			is PgArray -> {
				val array = obj.array
				if (array is Array<*>) getArrayStrings(array)
				else "\"\""
			}
			else -> handleString(obj.toString())
		}
	}
}

/**
 * 对字符串进行调整，特殊字符进行处理
 */
private fun handleString(o: String): String {
	return o.replace("\\", "\\\\");
}

private fun getArrayStrings(arr: Array<*>): String {
	return buildString {
		for (s in arr) {
			when (s) {
				null -> append("")
				is String -> append("\"").append(s).append("\"").append(",")
				is Int, is Long, is Double -> append(s).append(",")
				else -> append(handleString(s.toString())).append(",")
			}
		}
		if (isNotEmpty()) {
			delete(length - 1, length)
		}
		append("]")
		insert(0, "[")
	}
}
